package com.xuptGurantee.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuptGurantee.system.common.R;
import com.xuptGurantee.system.dto.ActivityDto;
import com.xuptGurantee.system.entity.Volunteer;
import com.xuptGurantee.system.service.ActivityDtoService;
import com.xuptGurantee.system.service.VolunteerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author zzzhc
 * @version 1.0
 * @description: TODO
 * @date 2022/10/8 21:16
 */
@Slf4j
@RequestMapping("/volunteer")
@RestController
public class VolunteerController {

    @Resource
    VolunteerService volunteerService;



    @PostMapping("/login")
    public R<Volunteer> login(HttpServletRequest request, @RequestBody Volunteer volunteer) {

        String password = volunteer.getVolunteerPass();
        LambdaQueryWrapper<Volunteer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Volunteer::getVolunteerStunum, volunteer.getVolunteerStunum());
        Volunteer volunteerServiceOne = volunteerService.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if (volunteerServiceOne == null) {
            return R.error("登录失败");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if (!volunteerServiceOne.getVolunteerPass().equals(password)) {
            return R.error("登录失败");
        }

        if (!(volunteerServiceOne.getVolunteerPermission().equals("admin") || volunteerService.getOne(queryWrapper).getVolunteerPermission().equals("superAdmin"))) {
            return R.error("需要管理员账号，权限不足");
        }

        //6、登录成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("admin", volunteerServiceOne.getId());
        return R.success(volunteerServiceOne);

    }

    @PostMapping("/logout")
    public R<String> login(HttpServletRequest request) {
        //清理Session中保存的当前登录员工的id
        request.getSession().removeAttribute("volunteer");
        return R.success("退出成功");
    }

    @PostMapping("/regisOrGrant")
    public R<String> regis(@RequestBody Volunteer volunteer) {
        LambdaQueryWrapper<Volunteer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Volunteer::getId, volunteer.getId());
        Volunteer volunteerServiceOne = volunteerService.getOne(queryWrapper);
        if (volunteerServiceOne != null) {
            if (!volunteerServiceOne.getVolunteerPermission().equals(volunteer.getVolunteerPermission())) {
                boolean grantRes = volunteerService.saveOrUpdate(volunteer);
                if (grantRes) {
                    return R.success("状态修改成功");
                }
            }
            return R.error("用户已存在");
        }
        if (volunteerService.save(volunteer)) {
            return R.success("注册成功");
        }
        return R.error("注册失败");
    }

    @PutMapping("/addTime")
    public R<String> addTime(@RequestBody Volunteer volunteer) {

        long id = Thread.currentThread().getId();
        log.info("线程id为：{}", id);
        volunteerService.updateById(volunteer);
        return R.success("信息修改成功");

    }


    @PutMapping("/modify")
    public R<String> modifyMember(@RequestBody Volunteer volunteer) {
        long id = Thread.currentThread().getId();
        log.info("线程id为：{}", id);
        Volunteer vol = volunteerService.getById(volunteer.getId());
        vol.setVolunteerTime(vol.getVolunteerTime() + volunteer.getVolunteerTime());
        volunteerService.updateById(vol);
        return R.success("信息修改成功");

    }

    /**
     * 修改员工帐号状态
     *
     * @param request
     * @return
     */
    @PutMapping("/modifyStatus")
    public R<String> modifyStatus(HttpServletRequest request, @RequestBody Volunteer volunteer) {
        Long empId = (Long) request.getSession().getAttribute("volunteer");
        LambdaQueryWrapper<Volunteer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Volunteer::getId, empId);
        if (!(volunteerService.getOne(queryWrapper).getVolunteerPermission().equals("admin") || volunteerService.getOne(queryWrapper).getVolunteerPermission().equals("superAdmin"))) {
            return R.error("没有权限！！!");
        }
        volunteerService.updateById(volunteer);
        return R.success("学生信息修改成功");
    }

    /**
     * 新增员工
     *
     * @param volunteer
     * @return
     */
    @PostMapping("/add")
    public R<String> addEmployee(HttpServletRequest request, @RequestBody Volunteer volunteer) {

        //设置初始密码123456，需要进行md5加密处理
        volunteer.setVolunteerPass(DigestUtils.md5DigestAsHex("123456".getBytes()));


        volunteerService.save(volunteer);

        return R.success("新增员工成功");
    }

    /**
     * 员工信息分页查询
     *
     * @param page
     * @param pageSize
     * @param stuNum   查询学生学号
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String stuNum) {
        log.info("page = {},pageSize = {},name = {}", page, pageSize, stuNum);

        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Volunteer> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(stuNum), Volunteer::getVolunteerStunum, stuNum);
        //添加排序条件
        queryWrapper.orderByDesc(Volunteer::getVolunteerStunum);

        //执行查询
        volunteerService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    /**
     * 根据id查询学生信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Volunteer> getById(@PathVariable Long id) {
        Volunteer volunteer = volunteerService.getById(id);
        if (volunteer != null) {
            return R.success(volunteer);
        }
        return R.error("没有查询到对应学生信息");
    }

    @DeleteMapping("/{id}")
    public R<String> deleteById(@PathVariable Long id) {
        if (volunteerService.removeById(id)) {
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }


}
